package leetcode.f1t100;

/**
 * 实现String.parseInt()
 *
 * https://leetcode.com/problems/string-to-integer-atoi/
 *
 * @author lichx
 * @date 2021/9/26 16:30
 */
public class Q8_StringToInteger {
    public int myAtoi(String s) {
        char[] c = s.toCharArray();
        int i = 0;
        int N = c.length;
        int ans = 0;
        while (i < N && c[i] == ' ') {
            i++;
        }
        if (i == N) {
            return ans;
        }
        boolean isNegative = c[i] == '-';
        if (c[i] == '-' || c[i] == '+') {
            i++;
        }
        while (i < N && c[i] >= '0' && c[i] <= '9') {
            int cur = c[i] - '0';
            if ((Integer.MAX_VALUE - cur) / 10 < ans || (Integer.MAX_VALUE - cur) / 10 == ans && cur > 7) {
                return isNegative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            }
            ans = ans * 10 + cur;
            i++;
        }
        return isNegative ? -ans : ans;
    }
}
